// Minus.cpp : implementation file
//

#include "stdafx.h"
#include "Difference.h"


// CMinus

CDifference::CDifference(BOOL resultInMinuend) : m_resultInMinuend(resultInMinuend)
{
}

CDifference::~CDifference()
{
}


// CMinus member functions

BOOL CDifference::Apply(CxImage& minuend, CxImage& subtrahend)
{
	// two operands must have the same size
	if (minuend.GetSize() != subtrahend.GetSize())
		return FALSE;

	if (minuend.ResetIteration() && subtrahend.ResetIteration())
	{
		RGBQUAD value1, value2;
		while (minuend.GetNextPixelColor(value1) && 
			subtrahend.GetNextPixelColor(value2))
		{
			value1.rgbRed -= value2.rgbRed;
			value1.rgbRed = (value1.rgbRed < 0) ? 0 : value1.rgbRed;
			value1.rgbGreen -= value2.rgbGreen;
			value1.rgbGreen = (value1.rgbGreen < 0) ? 0 : value1.rgbGreen;
			value1.rgbBlue -= value2.rgbBlue;
			value1.rgbBlue = (value1.rgbBlue < 0) ? 0 : value1.rgbBlue;

			if (m_resultInMinuend)
				minuend.SetCurrentPixel(value1);
			else
				subtrahend.SetCurrentPixel(value1);
		}
		return TRUE;
	}
	return FALSE;
}

BOOL CDifference::Apply(CxImage& minuend, CxImage& subtrahend, CxImage& result)
{
	// two operands must have the same size
	if (minuend.GetSize() != subtrahend.GetSize())
		return FALSE;

	if (minuend.ResetIteration() && subtrahend.ResetIteration() 
		&& result.ResetIteration())
	{
		RGBQUAD value1, value2;
		while (minuend.GetNextPixelColor(value1) && 
			subtrahend.GetNextPixelColor(value2))
		{
			value1.rgbRed -= value2.rgbRed;
			value1.rgbRed = (value1.rgbRed < 0) ? 0 : value1.rgbRed;
			value1.rgbGreen -= value2.rgbGreen;
			value1.rgbGreen = (value1.rgbGreen < 0) ? 0 : value1.rgbGreen;
			value1.rgbBlue -= value2.rgbBlue;
			value1.rgbBlue = (value1.rgbBlue < 0) ? 0 : value1.rgbBlue;

			result.SetNextPixelColor(value1);
		}
		return TRUE;
	}
	return FALSE;
}